{% extends "base.html" %}

{% block title %}发布文章 - 头条自动发文系统{% endblock %}
{% block page_title %}发布文章{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-8">
        <!-- 文章编辑 -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-edit text-primary"></i>
                    编辑文章
                </h5>
            </div>
            <div class="card-body">
                <form id="publish-form">
                    <div class="mb-3">
                        <label for="title" class="form-label">文章标题 *</label>
                        <input type="text" id="title" name="title" class="form-control form-control-lg" 
                               placeholder="请输入文章标题（建议30字以内）" maxlength="50" required>
                        <div class="form-text">
                            <span id="title-count">0</span>/50 字
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="content" class="form-label">文章内容 *</label>
                        <textarea id="content" name="content" class="form-control" rows="20" 
                                placeholder="请输入文章内容..." required></textarea>
                        <div class="form-text">
                            <span id="content-count">0</span> 字
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="cover-image" class="form-label">
                            封面图片 
                            <span class="text-danger">*</span>
                            <small class="text-muted">(必需)</small>
                        </label>
                        <div class="input-group">
                            <input type="file" id="cover-image" class="form-control" accept="image/*" required>
                            <button type="button" id="upload-cover" class="btn btn-outline-secondary" disabled>
                                <span class="loading spinner-border spinner-border-sm me-1" role="status"></span>
                                <i class="fas fa-upload"></i>
                                上传
                            </button>
                        </div>
                        <div class="form-text">
                            <span class="text-danger">
                                <i class="fas fa-exclamation-triangle"></i>
                                封面图片是发布的必需条件
                            </span><br>
                            选择JPG、PNG等图片格式，建议尺寸16:9
                        </div>
                        <div id="cover-preview" style="display: none;" class="mt-2">
                            <img id="cover-preview-img" src="" alt="封面预览" class="img-thumbnail" style="max-width: 200px;">
                            <div class="mt-1">
                                <small class="text-success">
                                    <i class="fas fa-check-circle"></i>
                                    封面图片已上传
                                </small>
                                <button type="button" id="remove-cover" class="btn btn-sm btn-outline-danger ms-2">
                                    <i class="fas fa-times"></i>
                                    移除
                                </button>
                            </div>
                        </div>
                        <input type="hidden" id="cover-path" name="cover_image" value="">
                    </div>
                    
                    <div class="d-flex justify-content-between">
                        <div>
                            <button type="button" id="save-draft" class="btn btn-outline-secondary">
                                <i class="fas fa-save"></i>
                                保存草稿
                            </button>
                            <button type="button" id="preview-btn" class="btn btn-outline-info">
                                <i class="fas fa-eye"></i>
                                预览
                            </button>
                        </div>
                        <div>
                            <button type="submit" class="btn btn-success">
                                <span class="loading spinner-border spinner-border-sm me-2" role="status"></span>
                                <i class="fas fa-paper-plane"></i>
                                立即发布
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <!-- 发布状态 -->
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-info-circle text-info"></i>
                    发布状态
                </h6>
            </div>
            <div class="card-body">
                {% if account %}
                <div class="d-flex align-items-center mb-3">
                    {% if account.avatar_url %}
                    <img src="{{ account.avatar_url }}" alt="头像" class="rounded-circle me-2" width="30" height="30">
                    {% endif %}
                    <div>
                        <div class="fw-bold">{{ account.nickname or account.username }}</div>
                        <small class="text-success">
                            <i class="fas fa-check-circle"></i>
                            已登录
                        </small>
                    </div>
                </div>
                {% else %}
                <div class="text-center">
                    <i class="fas fa-exclamation-triangle text-warning"></i>
                    <p class="text-muted">请先登录头条账号</p>
                    <a href="/login" class="btn btn-primary btn-sm">
                        <i class="fas fa-sign-in-alt"></i>
                        去登录
                    </a>
                </div>
                {% endif %}
            </div>
        </div>
        
        <!-- 草稿文章 -->
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-file-alt text-warning"></i>
                    草稿文章 ({{ articles|length }})
                </h6>
            </div>
            <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                {% if articles %}
                {% for article in articles %}
                <div class="border-bottom pb-2 mb-2">
                    <div class="fw-bold text-truncate" style="max-width: 200px;">
                        {{ article.title }}
                    </div>
                    <small class="text-muted">{{ article.created_at[:16] }}</small>
                    <div class="mt-1">
                        <button class="btn btn-sm btn-outline-primary load-draft" 
                                data-title="{{ article.title }}" 
                                data-content="{{ article.content }}">
                            <i class="fas fa-edit"></i>
                            编辑
                        </button>
                    </div>
                </div>
                {% endfor %}
                {% else %}
                <div class="text-center text-muted">
                    <i class="fas fa-file-alt fa-2x mb-2"></i>
                    <p>暂无草稿文章</p>
                    <a href="/generate" class="btn btn-sm btn-outline-primary">
                        <i class="fas fa-magic"></i>
                        生成文章
                    </a>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- 预览模态框 -->
<div class="modal fade" id="previewModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-eye text-info"></i>
                    文章预览
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="border rounded p-3" style="background-color: #f8f9fa;">
                    <h3 id="preview-title" class="mb-3"></h3>
                    <div id="preview-content" style="white-space: pre-line; line-height: 1.6;"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 发布确认模态框 -->
<div class="modal fade" id="publishModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-paper-plane text-success"></i>
                    确认发布
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>确定要发布这篇文章吗？</p>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle"></i>
                    文章发布后将在头条平台展示，请确保内容准确无误。
                </div>
                <div class="row">
                    <div class="col-sm-3"><strong>标题：</strong></div>
                    <div class="col-sm-9" id="confirm-title"></div>
                </div>
                <div class="row mt-2">
                    <div class="col-sm-3"><strong>字数：</strong></div>
                    <div class="col-sm-9"><span id="confirm-count"></span> 字</div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" id="confirm-publish" class="btn btn-success">
                    <span class="loading spinner-border spinner-border-sm me-2" role="status"></span>
                    <i class="fas fa-paper-plane"></i>
                    确认发布
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 字数统计
    function updateCount() {
        const titleLength = $('#title').val().length;
        const contentLength = $('#content').val().length;
        
        $('#title-count').text(titleLength);
        $('#content-count').text(contentLength);
    }
    
    $('#title, #content').on('input', function() {
        updateCount();
        updatePublishButton(); // 更新发布按钮状态
    });
    
    // 图片上传相关
    $('#cover-image').change(function() {
        const file = this.files[0];
        if (file) {
            // 检查文件类型
            if (!file.type.startsWith('image/')) {
                showAlert('请选择图片文件', 'warning');
                $(this).val('');
                return;
            }
            
            // 检查文件大小（5MB限制）
            if (file.size > 5 * 1024 * 1024) {
                showAlert('图片文件不能超过5MB', 'warning');
                $(this).val('');
                return;
            }
            
            $('#upload-cover').prop('disabled', false);
            
            // 显示预览
            const reader = new FileReader();
            reader.onload = function(e) {
                $('#cover-preview-img').attr('src', e.target.result);
                $('#cover-preview').show();
            };
            reader.readAsDataURL(file);
        } else {
            $('#upload-cover').prop('disabled', true);
            $('#cover-preview').hide();
        }
    });
    
    // 检查发布按钮状态
    function updatePublishButton() {
        const title = $('#title').val().trim();
        const content = $('#content').val().trim();
        const coverPath = $('#cover-path').val().trim();
        
        const canPublish = title && content && coverPath;
        $('#publish-form button[type="submit"]').prop('disabled', !canPublish);
        
        if (!canPublish) {
            $('#publish-form button[type="submit"]').addClass('btn-secondary').removeClass('btn-success');
        } else {
            $('#publish-form button[type="submit"]').removeClass('btn-secondary').addClass('btn-success');
        }
    }
    
    // 上传封面图片
    $('#upload-cover').click(function() {
        const fileInput = $('#cover-image')[0];
        const file = fileInput.files[0];
        
        if (!file) {
            showAlert('请先选择图片文件', 'warning');
            return;
        }
        
        const formData = new FormData();
        formData.append('file', file);
        
        showLoading(this, true);
        
        $.ajax({
            url: '/api/upload-cover',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    $('#cover-path').val(response.file_path);
                    showAlert('封面图片上传成功', 'success');
                    $('#upload-cover').text('已上传').addClass('btn-success').removeClass('btn-outline-secondary');
                    updatePublishButton(); // 更新发布按钮状态
                } else {
                    showAlert(response.message, 'danger');
                }
            },
            error: function() {
                showAlert('图片上传失败，请重试', 'danger');
            },
            complete: function() {
                showLoading('#upload-cover', false);
            }
        });
    });
    
    // 移除封面图片
    $('#remove-cover').click(function() {
        $('#cover-image').val('');
        $('#cover-path').val('');
        $('#cover-preview').hide();
        $('#upload-cover').prop('disabled', true).text('上传').removeClass('btn-success').addClass('btn-outline-secondary');
        updatePublishButton(); // 更新发布按钮状态
    });
    
    // 加载草稿
    $('.load-draft').click(function() {
        const title = $(this).data('title');
        const content = $(this).data('content');
        
        $('#title').val(title);
        $('#content').val(content);
        updateCount();
        
        showAlert('草稿已加载', 'success');
    });
    
    // 保存草稿
    $('#save-draft').click(function() {
        const title = $('#title').val().trim();
        const content = $('#content').val().trim();
        
        if (!title || !content) {
            showAlert('标题和内容不能为空', 'warning');
            return;
        }
        
        // 这里可以添加保存草稿的逻辑
        showAlert('草稿已保存', 'success');
    });
    
    // 预览文章
    $('#preview-btn').click(function() {
        const title = $('#title').val().trim();
        const content = $('#content').val().trim();
        
        if (!title || !content) {
            showAlert('请先填写标题和内容', 'warning');
            return;
        }
        
        $('#preview-title').text(title);
        $('#preview-content').text(content);
        $('#previewModal').modal('show');
    });
    
    // 发布表单提交
    $('#publish-form').submit(function(e) {
        e.preventDefault();
        
        const title = $('#title').val().trim();
        const content = $('#content').val().trim();
        const coverPath = $('#cover-path').val().trim();
        
        if (!title || !content) {
            showAlert('标题和内容不能为空', 'warning');
            return;
        }
        
        if (!coverPath) {
            showAlert('请先上传封面图片，封面图片是发布的必需条件', 'warning');
            return;
        }
        
        {% if not account %}
        showAlert('请先登录头条账号', 'warning');
        setTimeout(function() {
            window.location.href = '/login';
        }, 2000);
        return;
        {% endif %}
        
        // 显示确认对话框
        $('#confirm-title').text(title);
        $('#confirm-count').text(content.length);
        $('#publishModal').modal('show');
    });
    
    // 确认发布
    $('#confirm-publish').click(function() {
        const title = $('#title').val().trim();
        const content = $('#content').val().trim();
        const coverPath = $('#cover-path').val().trim();
        
        showLoading(this, true);
        showLoading('#publish-form button[type="submit"]', true);
        
        $.post('/api/publish-article', {
            title: title,
            content: content,
            cover_image: coverPath
        })
        .done(function(response) {
            if (response.success) {
                showAlert('文章发布成功！', 'success');
                $('#publishModal').modal('hide');
                
                // 清空表单
                $('#title').val('');
                $('#content').val('');
                updateCount();
                
                // 跳转到监控页面
                setTimeout(function() {
                    window.location.href = '/monitor';
                }, 2000);
            } else {
                showAlert(response.message, 'danger');
            }
        })
        .fail(function() {
            showAlert('发布失败，请检查网络连接', 'danger');
        })
        .always(function() {
            showLoading('#confirm-publish', false);
            showLoading('#publish-form button[type="submit"]', false);
        });
    });
    
    // 获取URL参数中的文章ID（如果有）
    const urlParams = new URLSearchParams(window.location.search);
    const articleId = urlParams.get('id');
    
    if (articleId) {
        // 这里可以加载指定文章的内容
        // 目前先显示提示
        showAlert('正在加载文章...', 'info');
    }
    
    // 初始化字数统计和发布按钮状态
    updateCount();
    updatePublishButton();
});
</script>
{% endblock %}
